import { expect } from '@jest/globals';
import * as fse from 'fs-extra';
import path from 'path';

import { buildOneHapAndCheckFile, buildServiceCard, decompressHapAndReadEntries } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 添加服务卡片
  const entryPath = project.getModule('entry').moduleRootPath();
  await buildServiceCard(entryPath, 'HelloWorld', 'Image', 'Immersive');

  // 2. 执行hap构建
  await buildOneHapAndCheckFile('entry')(project, taskConfig, record);

  // 3. 校验hap包产物
  const outPutPath = path.resolve(entryPath, 'build', 'default', 'outputs', 'default');
  const hapName = (await fse.readdir(outPutPath)).filter(item => item.endsWith('-signed.hap'))[0];
  const hapFiles = await decompressHapAndReadEntries(path.resolve(outPutPath, hapName));
  const fileNames = hapFiles.map(item => item[0]);
  const hasAbc = fileNames.includes('ets/modules.abc') && fileNames.includes('ets/widgets.abc');
  expect(hasAbc).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_ZOS_HOS_Build_ArkTs_Service_Widge_api10_002')
  .description('002、支持工程内新建Arkts卡片编译打包')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).sign(SignType.Sign).build())
  .testFun(testFun)
  .load();
